import React from 'react';
import { Button, Table, Modal, message } from 'antd';

import Search from 'antd/lib/input/Search';
import { ColumnsType } from 'antd/lib/table';

import { TTSInfo } from '../../../schema/TTS';
import { getTTSList, deleteTTS } from '../../../servers/servers';
import { clearNull, deleteRowChangePageNum, getTableIndex } from '../../../../utils/tools';
import { TTSPop } from './component/TTSPop';
import './style.scss';
import { checkPermission } from 'permission/Index';

/**
 * TTS厂商管理props
 */
interface IProps {}
/**
 * TTS厂商管理state
 */
export interface IState {
  // TTS厂商名称
  ttsManufacturerName: string;
  // 新增TTS厂商抽屉控件显隐
  operationVisible: boolean;
  // 展示在table的数据
  tableData: TTSInfo[];
  // 详情对话框是否显示
  detailVisible: boolean;
  // 当前选中所要查看详情的数据
  current?: TTSInfo;
  // 分页相关数据
  pageInfo: {
    pageTotal: number;
    pageNum: number;
    pageSize: number;
  };
  tableLoading: boolean;
}

/**
 * TTS厂商管理页
 */
class TTS extends React.Component<IProps, IState> {
  /**
   * table列头
   * 因为table列头相对固定，不需要响应式地修改视图，所以记录在类的私有属性中而不是react state中，轻量的state利于提升性能
   */
  private columns: ColumnsType<TTSInfo>;

  //子组件 TTS厂商操作 的引用
  private operationRef: React.RefObject<TTSPop> | undefined;

  constructor(props: IProps) {
    super(props);
    // 初始数据
    this.state = {
      ttsManufacturerName: '',
      detailVisible: false,
      operationVisible: false,
      current: undefined,
      tableData: [],
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: false,
    };

    this.columns = [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        key: 'index',
        render: (text, record, index) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      },
      {
        title: 'TTS厂商名称',
        dataIndex: 'ttsManufacturerName',
        key: 'ttsManufacturerName',
        width: 200,
      },
      {
        title: '唯一标识',
        dataIndex: 'ttsManufacturerIdentifier',
        key: 'ttsManufacturerIdentifier',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        width: 200,
        render: (text, record, index) => {
          return this.renderOperation(text, record, index);
        },
      },
    ];
    this.operationRef = React.createRef();
  }

  public componentDidMount() {
    this.fetchList();
  }

  /**
   * 渲染操作按钮
   */
  private renderOperation(text: any, record: TTSInfo, index: number): JSX.Element {
    return (
      <>
        {checkPermission('/system/tts/modify') && (
          <Button
            type="link"
            onClick={() => {
              this.modify(record);
            }}
          >
            编辑
          </Button>
        )}
        {checkPermission('/system/tts/delete') && (
          <Button
            type="link"
            onClick={() => {
              this.deleteRecord(record);
            }}
          >
            删除
          </Button>
        )}
      </>
    );
  }

  /**
   * 根据TTS厂商名称查询列表
   */
  private searchTTS(name: string) {
    this.setState(
      {
        ttsManufacturerName: name.trim(),
      },
      () => {
        this.jumpPage(1);
      }
    );
  }

  /**
   * 编辑TTS厂商交互
   */
  private modify(record: TTSInfo) {
    const modal = this.operationRef?.current;
    modal && modal.open('modify');
    modal && modal.setValue(record);
  }

  /**
   * 删除TTS厂商交互
   */
  private deleteRecord(record: TTSInfo) {
    Modal.confirm({
      content: '删除TTS厂商后无法恢复，确定删除吗',
      onOk: () => {
        deleteTTS(record.ttsManufacturerId)
          .then(res => {
            if (res.code === 0) {
              message.success('删除成功');
              this.deleteFresh(1);
            } else {
              message.error(`${res.tips}(错误码: ${res.code})`);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }

  /**
   * 获取列表数据
   */
  private fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { ttsManufacturerName, pageInfo } = this.state;
    getTTSList(
      clearNull({
        ttsManufacturerName: ttsManufacturerName,
        pageNo: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
      })
    )
      .then(res => {
        this.setState({
          tableLoading: false,
        });
        pageInfo.pageTotal = res.count as number;
        this.setState({
          tableData: res.data,
          pageInfo: pageInfo,
        });
      })
      .catch(error => {
        this.setState({
          tableLoading: false,
        });
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * 删除-数据后更新
   */
  private deleteFresh(size: number) {
    const { pageTotal, pageNum, pageSize } = this.state.pageInfo;
    const newPageNum = deleteRowChangePageNum(size, pageTotal, pageNum, pageSize);
    this.setState(
      {
        pageInfo: {
          pageTotal,
          pageSize,
          pageNum: newPageNum,
        },
      },
      () => {
        this.fetchList();
      }
    );
  }

  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }
  render() {
    const {
      tableData,
      tableLoading,
      pageInfo: { pageNum, pageSize, pageTotal },
    } = this.state;

    return (
      <>
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Search
              className="mgr-header-search"
              placeholder="请输入TTS厂商名称"
              enterButton="搜索"
              onSearch={value => this.searchTTS(value)}
            />
          </div>
          <div className="mgr-header-right">
            {checkPermission('/system/tts/add') && (
              <Button
                type="primary"
                onClick={() => {
                  this.operationRef?.current?.open('create');
                }}
              >
                新建TTS厂商
              </Button>
            )}
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            columns={this.columns}
            dataSource={tableData}
            rowKey={record => record.ttsManufacturerId as number}
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <TTSPop
          ref={this.operationRef}
          callback={id => {
            id ? this.fetchList() : this.jumpPage(1);
          }}
        />
      </>
    );
  }
}

export default TTS;
